import { TilingSprite,Texture} from "pixi.js";
import { TexturePool } from "@/utils/TexturePool.js";
import { ImageManager } from "@/managers/ImageManager.js";
import { ToneFilter } from "@/filters/ToneFilter.js";

export class Sprite_WindowBackground extends TilingSprite{
    static texture=null;
    constructor(width,height){
        let ctor=new.target;
        if(!ctor.texture){
            ctor.texture=TexturePool.newTexture();
            ImageManager.loadSystem('Tiling').then(source=>{
                let texture=this.constructor.texture;
                texture.source=source;
                texture.noFrame=true;
                texture.update();
                texture.noFrame=false;
            });
        }
        super({
            texture:ctor.texture,
            width,
            height
        });

        this.toneFilter=null;
        if(!ctor.texture.refCount){
            ctor.texture.refCount=0;
        }
        ++ctor.texture.refCount;
    }

    resize(width,height){
        this.setSize(width,height);
    }

    destroy(opts){
        opts=opts||{children:true};
        if(opts.texture){
            opts.texture=false;
        }
        if(opts.textureSource){
            opts.textureSource=false;
        }

        let ctor=this.constructor;
        this.texture=Texture.EMPTY;
        Texture.EMPTY.off('update',this.onViewUpdate,this);

        --ctor.texture.refCount;
        if(ctor.texture.refCount<=0){
            ImageManager.releaseSystem('Tiling');
            TexturePool.releaseTexture(ctor.texture);
            ctor.texture=null;
        }
        super.destroy(opts);
    }

    setTone(r,g,b){
        if(r!=0||g!=0||b!=0){
            if(!this.toneFilter){
                this.toneFilter=new ToneFilter();
                this.filters=[this.toneFilter];
            }else{
                this.toneFilter.enabled=true;
            }
            this.toneFilter.setTone(r/255,g/255,b/255);
        }else if(this.toneFilter){
            this.toneFilter.enabled=false;
        }
    }
}